package com.tyf.util;

import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
/*import org.apache.pdfbox.pdmodel.graphics.xobject.PDXObjectImage;*/
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.sl.usermodel.PictureData;
import org.apache.poi.sl.usermodel.SlideShow;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFPictureData;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;

import static com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolver.iterator;

/**
 * 读取office文件图片 且安放到配置文件路径下 所有方法，两个共同参数、我呢见
 */
public class OfficeOfPicture {
    /**
     * 定义一个文件存放路径，后期会配置到application.yml下
     */
    private static String targetFolder = "D:\\english_path\\";
    /**
     * 用于处理pptx提取图片，返回一个存储6路径名称  传入一个 文件路径以及POI的读取文件内容的参数
     */
    public static List<File> pptPicture(XMLSlideShow xmlslideShow) throws IOException {
        List<File> listFile = new ArrayList<File>();
        if(xmlslideShow == null){
            return null;
        }
        List pictures = xmlslideShow.getPictureData();
        File file = null;
        for (int i = 0; i < pictures.size(); i++) {
            PictureData picture = (PictureData) pictures.get(i);
            file = new File(targetFolder + UUID.randomUUID() + ".jpg");
            FileOutputStream out = new FileOutputStream(file);
            out.write(picture.getData());
            out.close();
            listFile.add(file);
        }
        return listFile;
    }
    /**
     * 用于处理ppt提取图片，返回一个存储路径名称  传入一个 文件路径以及POI的读取文件内容的参数
     */
    public static List<File> pptxPicture(SlideShow slideShow) throws IOException {
        List<File> listFile = new ArrayList<File>();
        File file = null;
        // 图片内容
        List pictures = slideShow.getPictureData();
        for (int i = 0; i < pictures.size(); i++) {
            PictureData picture = (PictureData) pictures.get(i);
            file = new File( targetFolder + "/" + UUID.randomUUID() + ".jpg");
            FileOutputStream out = new FileOutputStream(file);
            out.write(picture.getData());
            out.close();
            listFile.add(file);
        }
        return listFile;
    }

    /**
     * PDF提取图片方法  抛弃  基于 pdfbox 1.8.13 原因是因为tika 1.21版本和pdf1.8.13版本内部jar包冲突
     * 图片名称拼接为文件名称 + _ + 循环次数
     */
  /*  public static List<File> pdfPicture(File file) throws IOException {
        List<File> listFile = new ArrayList<File>();
        File newPdf = null;
        if(file == null){
            return null;
        }
        PDDocument document = PDDocument.load(file);
        PDDocumentCatalog documentCatalog = document.getDocumentCatalog();

        List allPages = documentCatalog.getAllPages();
        Iterator<PDPage> iter = allPages.iterator();

        int count = 0;
        while(iter.hasNext()){
            //获取到图片并判断非空
            Map<String, PDXObjectImage> images = iter.next().getResources().getImages();
            if(images != null){
                Iterator<String> imageIter = images.keySet().iterator();
                while(imageIter.hasNext()){
                    //循环次数自增，来源是图片数量
                    count++;
                    // 拼接图片文件名
                    newPdf = new File(targetFolder + "/" + UUID.randomUUID() + ".jpg");
                    // 保存图片
                    images.get(imageIter.next()).write2file(newPdf);

                    listFile.add(newPdf);
                }
            }
        }
        return listFile;
    }*/

    /**
     * pdf转换图片
     * @param file
     * @return
     * @throws IOException
     */
    public static List<File> pdfPicture(File file) throws IOException {
        List<File> listFile = new ArrayList<File>();
        File newPdf = null;
        if(file == null){
            return null;
        }
        PDDocument document = PDDocument.load(file);
        PDDocumentCatalog documentCatalog = document.getDocumentCatalog();
        int numberOfPages = document.getNumberOfPages();
        for(int i=0;i<numberOfPages;i++){
            PDPage page = document.getPage(i);
            PDResources resources = page.getResources();
            Iterable<COSName> xObjectNames = resources.getXObjectNames();
            File file1 = null;
            if(xObjectNames != null){
                Iterator<COSName> iterator = xObjectNames.iterator();
                while (iterator.hasNext()){
                    COSName next = iterator.next();
                    if(resources.isImageXObject(next)){
                        try {
                            PDImageXObject image = (PDImageXObject) resources.getXObject(next);
                            file1 = new File(targetFolder+ "/" + UUID.randomUUID() +".jpg");
                            FileOutputStream fos = new FileOutputStream(file1);
                            listFile.add(file1);
                            BufferedImage bufferedImage = image.getImage();
                            ImageIO.write(bufferedImage, "jpeg", fos);
                        }catch (Exception e){
                            throw new FileNotFoundException("解析异常");
                        }
                    }
                }
            }
        }
        return listFile;
    }
    /**
     * 从word的doc里面提取图片
     * 文件名为uuid  + 文件后缀
     * @return
     */
    public static List<File> docPicture(String file) throws IOException {
        if(file == null){
            return null;
        }
        HWPFDocument hwpfDocument = new HWPFDocument(new FileInputStream(file));
        List<Picture> allPictures = hwpfDocument.getPicturesTable().getAllPictures();
        List<File> listFile = new ArrayList<File>();
        File docFileImage = null;
        for (Picture pic : allPictures){
            docFileImage = new File(targetFolder + "/" + UUID.randomUUID() + ".png");
            FileOutputStream fos = new FileOutputStream(docFileImage);
            fos.write(pic.getContent());
            fos.close();
            listFile.add(docFileImage);
        }
        return listFile;

    }
    /**
     * 从word的docx里面提取图片
     * 文件名为uuid + 文件后缀
     * @return
     */
    public static List<File> docxPicture(String srcFile) throws IOException {
        List<File> fileList = new ArrayList<File>();
        if(srcFile == null){
            return null;
        }
        File file = new File(srcFile);
        try {
            FileInputStream fis = new FileInputStream(file);
            // 用XWPFDocument的getAllPictures来获取所有的图片
            List<XWPFPictureData> picList = new XWPFDocument(fis).getAllPictures();
            File docxFile = null;
            for (XWPFPictureData pic : picList) {
                byte[] bytev = pic.getData();
                // 大于300bites的图片我们才弄下来，消除word中莫名的小图片的影响
                if (bytev.length > 300) {
                    docxFile = new File(targetFolder + "/" + UUID.randomUUID() + pic.getFileName());
                    FileOutputStream fos = new FileOutputStream(docxFile);
                    fos.write(bytev);
                    fos.close();
                    fileList.add(docxFile);
                }
            }
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileList;
    }
}

